﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Facebook;
using System.Dynamic;
using System.IO;
using System.Net;
using System.Windows.Threading;
using System.Threading;

namespace iMagistic
{
    /// <summary>
    /// Interaction logic for FacebookModule.xaml
    /// </summary>
    public partial class FacebookModule : Window
    {
        private Uri loginUrl;
        public bool isDownloading = false;
        FacebokFolder fFolder = new FacebokFolder();
        public List<string> photoPaths { get; set; }
        Thread DownloaderThread;
        public FacebookModule()
        {
            InitializeComponent();

            var appId = "363913673657957";
            string[] extendedPermissions = new[] { "user_about_me", "user_photos" };
            this.loginUrl = GenerateLoginUrl(appId, extendedPermissions);
        }


        public FacebookModule(FacebokFolder tmpFf, FacebookOAuthResult result)
        {
            InitializeComponent();
            fFolder.Name = tmpFf.Name;
            fFolder.photos = tmpFf.photos;
            this.FacebookOAuthResult = result;
            this.photoPaths = new List<string>();
            isDownloading = true;

            DownloaderThread = new Thread(DownloadImage);
            DownloaderThread.SetApartmentState(ApartmentState.STA);
            DownloaderThread.IsBackground = true;
            this.Height = 240;
            this.Width = 550;


        }

        private Uri GenerateLoginUrl(string appId, string[] extendedPermissions)
        {

            // for .net 3.5
            // var parameters = new Dictionary<string,object>
            // parameters["client_id"] = appId;
            dynamic parameters = new ExpandoObject();
            parameters.client_id = appId;
            parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";

            // The requested response: an access token (token), an authorization code (code), or both (code token).
            parameters.response_type = "token";

            // list of additional display modes can be found at http://developers.facebook.com/docs/reference/dialogs/#display
            parameters.display = "popup";

            // add the 'scope' parameter only if we have extendedPermissions.
            if (extendedPermissions != null)
                parameters.scope = extendedPermissions;

            // generate the login url
            var fb = new FacebookClient();
            return fb.GetLoginUrl(parameters);
        }

        private void webBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            var fb = new FacebookClient();
            FacebookOAuthResult oauthResult;
            if (fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
            {
                this.FacebookOAuthResult = oauthResult;
                this.Close();
            }
            else
            {
                this.FacebookOAuthResult = null;
            }
        }

        public FacebookOAuthResult FacebookOAuthResult { get; set; }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (!isDownloading)
                webBrowser.Navigate(this.loginUrl);
            else
            {

                DownloaderThread.Start();
            }

        }

        private void webBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            webBrowser.Visibility = System.Windows.Visibility.Visible;
        }

        private void closeBtn_Click(object sender, RoutedEventArgs e)
        {
            if ((DownloaderThread != null) && (DownloaderThread.IsAlive))
                DownloaderThread.Abort();
            this.Close();
        }

        public List<FacebokFolder> GetFacebookFolders()
        {
            var fb = new FacebookClient(FacebookOAuthResult.AccessToken);

            dynamic result = fb.Get("/me");
            //var name = result.name;p
            string id = (string)result["id"];

            string query = "SELECT aid,name FROM album WHERE owner=" + id;
            string query2 = "SELECT aid,src_big FROM photo WHERE aid IN (SELECT aid  FROM album WHERE owner='" + id + "')";

            result = fb.Get("fql", new { q = new[] { query, query2 } });

            var folders = result["data"][0];
            var photos = result["data"][1];

            var FoldersDict = (folders["fql_result_set"] as Facebook.JsonArray).ToDictionary(
                                p => (p as Facebook.JsonObject)["aid"].ToString(),
                                p => (p as Facebook.JsonObject)["name"].ToString());

            var PhotosDict = (photos["fql_result_set"] as Facebook.JsonArray).ToDictionary(
                                p => (p as Facebook.JsonObject)["src_big"].ToString(),
                                p => (p as Facebook.JsonObject)["aid"].ToString());


            Dictionary<string, FacebokFolder> myPhotoFoldersDict = new Dictionary<string, FacebokFolder>();

            foreach (var item in FoldersDict)
            {
                string name = item.Value.ToString();
                string aid = item.Key.ToString();
                FacebokFolder ff = new FacebokFolder();
                ff.Name = name;
                myPhotoFoldersDict.Add(aid, ff);
            }

            foreach (var item in PhotosDict)
            {
                string src_big = item.Key;
                string aid = item.Value;
                myPhotoFoldersDict[aid].photos.Add(src_big);
            }

            List<FacebokFolder> FoldersList = new List<FacebokFolder>();
            foreach (var item in myPhotoFoldersDict)
            {
                FoldersList.Add(item.Value);
            }
            return FoldersList;
        }

        public void DownloadImage()
        {
            List<string> imgUrls = fFolder.photos;
            string facebookFolderName = fFolder.Name;
            try
            {
                this.Dispatcher.Invoke(DispatcherPriority.Normal,
                   (Action)delegate()
                   {
                       DialogName.Content = "Downloading";
                       browsingGrid.Visibility = System.Windows.Visibility.Hidden;
                       downloadingGrid.Visibility = System.Windows.Visibility.Visible;
                   });


                string folderToSave = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + Path.DirectorySeparatorChar + "iMagistic";

                WebClient client = new WebClient();


                foreach (string url in imgUrls)
                {
                    string subFolderToSave = folderToSave + Path.DirectorySeparatorChar + facebookFolderName;

                    this.Dispatcher.Invoke(DispatcherPriority.Normal,
                   (Action)delegate()
                   {
                       folderName.Content = facebookFolderName;
                       amount.Content = imgUrls.IndexOf(url).ToString() + " out of " + imgUrls.Count.ToString();
                   }
                );
                    Directory.CreateDirectory(subFolderToSave);
                    string photoPath = subFolderToSave + Path.DirectorySeparatorChar + Path.GetFileName(url);
                    client.DownloadFile(url, photoPath);
                    this.photoPaths.Add(photoPath);

                    this.Dispatcher.Invoke(DispatcherPriority.Normal,
                  (Action)delegate()
                  {
                      double progress = (double)(imgUrls.IndexOf(url) + 1);
                      progress = (double)progress / imgUrls.Count * 100;
                      progressBar.Value = progress;
                  });

                }
            }
            catch (Exception e)
            {
                //MessageBox.Show(e.Message.ToString());
            }

            this.Dispatcher.Invoke(DispatcherPriority.Normal,
                  (Action)delegate()
                  { this.Close(); });
        }
    }

    public class FacebokFolder
    {
        public string Name { get; set; }
        public List<string> photos { get; set; }

        public FacebokFolder()
        {
            photos = new List<string>();
        }
    }





}
